<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-col :span="19">
            <el-button
              style="float: left"
              type="primary"
              @click="addUserCenterDialogVisible = true"
              round
            >添加用户</el-button>
          </el-col>
          <el-col :span="5">
            <el-input
              placeholder="请输入内容"
              v-model="queryData.query"
              class="input-with-select"
              @clear="getUserList"
              clearable
            >
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
        </el-row>
      </div>
      <!-- 用户列表表格 -->
      <el-table :data="users" stripe style="width: 100%">
        <el-table-column type="index" label="序号" class="indexCol"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userstateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="操作">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                @click="getEditUser(scope.row)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                round
                class="r_btns"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="open(scope.row.id)"
                round
                class="r_btns"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                @click="setRoles(scope.row)"
                type="success"
                icon="el-icon-setting"
                size="mini"
                round
                class="r_btns"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addUserCenterDialogVisible"
      width="30%"
      @close="resetAddForm"
      center
    >
      <el-form
        :model="addUserForm"
        :rules="addUserRules"
        ref="addUserRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserCenterDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="editUserCenterDialogVisible"
      width="30%"
      @close="resetEditForm"
      center
    >
      <el-form ref="editUserRef" :model="editUserForm" :rules="editUserRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserCenterDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对跨框 -->
    <el-dialog @close="setRoleDialogClose" title="分配角色" :visible.sync="setRoleDialogVisible" width="30%" center>
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>分配新角色：
        <el-select v-model="rolesSelectValue" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleSub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 定义邮箱验证规则
    const checkEmail = (rule, value, cb) => {
      if (!value) return cb(new Error("邮箱不能为空"));
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      if (reg.test(value)) return cb();
      cb(new Error("邮箱格式不正确"));
    };
    // 定义手机号验证规则
    const checkMobile = (rule, value, cb) => {
      if (!value) return cb(new Error("手机号不能为空"));
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (reg.test(value)) return cb();
      cb(new Error("手机号格式不正确"));
    };
    return {
      queryData: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      users: [],
      total: 0,
      // 控制添加用户对话框
      addUserCenterDialogVisible: false,
      //添加用户数据对象
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      addUserRules: {
        username: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //修改用户
      editUserCenterDialogVisible: false,
      editUserForm: {
        email: "",
        mobile: ""
      },
      //修改用户规则
      editUserRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //分配角色对话框
      setRoleDialogVisible: false,
      // 分配角色的信息
      userInfo: {},
      //角色列表数据
      rolesList: [],
      //分配角色的下拉菜单
      rolesSelectValue: ""
    };
  },

  created() {
    this.getUserList();
  },

  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryData
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.users = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(val) {
      this.queryData.pagesize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.queryData.pagenum = val;
      this.getUserList();
    },
    async userstateChange(row) {
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      );
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state;
        return this.$message.error("修改失败");
      }
      this.$message.success("修改成功");
    },
    resetAddForm() {
      this.$refs.addUserRef.resetFields();
    },
    //添加用户
    addUser() {
      this.$refs.addUserRef.validate(async flag => {
        if (!flag) return;
        const { data: res } = await this.$http.post("users", this.addUserForm);
        console.log(res);
        if (res.meta.status !== 201) return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功");
        this.addUserCenterDialogVisible = false;
        // 重新获取表单数据
        this.getUserList();
      });
    },
    // 修改用户
    async getEditUser(row) {
      this.editUserCenterDialogVisible = true;
      const { data: res } = await this.$http.get("users/" + row.id);
      this.editUserForm = res.data;
    },
    // 重置修改用户表单
    resetEditForm() {
      this.$refs.editUserRef.resetFields();
    },
    //修改用户提交
    editUser() {
      this.$refs.editUserRef.validate(async flag => {
        if (!flag) return;
        console.log(this.editUserForm);
        const { data: res } = await this.$http.put(
          "users/" + this.editUserForm.id,
          this.editUserForm
        );
        if (res.meta.status != 200)
          return this.$message.error("用户数据修改失败");
        this.$message.success("用户数据修改成功");
        this.editUserCenterDialogVisible = false;
        this.getUserList();
      });
    },
    // 删除确认框
    open(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const {data:res} = await this.$http.delete(`users/${id}`);
          if(res.meta.status!==200)return this.$message.error('删除失败');
          this.$message.success('删除成功');
          this.getUserList();
        })
        .catch(() => {
          this.$message.info('已取消删除')
        });
    },
    // 打开分配角色对话框
    async setRoles(row) {
      this.setRoleDialogVisible = true;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("加载失败");
      this.rolesList = res.data;
      this.userInfo = row;
    },
    // 点击确定提交分配角色
    async setRoleSub() {
      if (!this.rolesSelectValue) return this.$message.error("请选择角色");
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.rolesSelectValue});
      if (res.meta.status !== 200) return this.$message.error("分配角色失败");
      this.$message.success("分配角色成功");
      this.setRoleDialogVisible = false;
      this.getUserList();
    },
    // 分配角色对话框关闭
    setRoleDialogClose(){
      this.rolesSelectValue=''
    }
  }
};
</script>

<style scoped lang='less'>
.el-breadcrumb {
  margin-bottom: 20px;
  padding: 15px;
}
.iel-table_1_column_1 .cell div {
  text-align: center !important;
}
</style>
